<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\model\OrderModel;
use app\model\CatModel;
use app\model\UserModel;
use app\model\DeptModel;
use app\Common;


class Order{
    //常用数据表内容 及常用字典

    var $cat=[];
    var $dept=[];
    var $users=[];
    var $bg;
    var $sys;
    var $stars=array(0=>'',1=>'★☆☆☆☆',2=>'★★☆☆☆',3=>'★★★☆☆',4=>'★★★★☆',5=>'★★★★★');    

    //['name','english name','next statue','view name']
    var $status=array(
        '1'=> array('新单',    'New order',   '2','付款'),
        '2'=> array('已付款', 'Taked','3','发货'),
        '3'=> array('已发货', 'Sent','4','收货'),
        '4'=> array('已收货', 'Recevied','5','评价'),
        '5'=> array('已评价', 'comment','6',''),
        '6'=> array('已退货','Return','',''),
        '10'=>array('客人取消', 'Canceled by Customer ','0',''),
        '20'=>array('商家取消', 'Canceled by Shop','0',''),
        '30'=>array('平台取消','Canceled',0,'')
    );

    var $discount =[];
    var $payment = array('wx'=>'微信','alipay'=>'支付宝','cash'=>'现金');
    var $type = array('1'=>'服务单','2'=>'商品单');


    //构造器
    public function __construct(){
        $catM=new CatModel();
        $this->cat = $catM->catTree(1); 
        $um=new UserModel();
        $this->users = $um->getAll();
        $dm=new DeptModel();
        $this->dept = $dm->getAll();

        for($dis=100;$dis>50;$dis-=5){
            $this->discount[]= ['value'=>$dis/100,'desc'=>$dis.'%'];
        }
        $this->sys = Db::table('sys')->find(1);

    }

    //我的订单
    public function my_orders(){
        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'需要token!']);
        }
        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }
        $customer=$arr['customer'];
        
        if($customer['credit']<=50){
            //return json(array('code'=>0,'msg'=>'很抱歉，你的信用分只有'.$customer['credit'].'分!'));
        }

        //店主或者用户订单
        if($customer['type']!=2){
            $list = Db::table('order')->where('customer_id',$customer['id'])->order('create_time','desc')->paginate(20)->toArray();  
        }else{
            $list = Db::table('order')->whereRaw('dept_id='.$customer['dept_id']. " or customer_id=".$customer['id'])->order('create_time')->paginate(20)->toArray();  
        }
    
        foreach($list['data'] as &$kv){
            $cust = Db::table('customer')->where('id',$kv['customer_id'])->column('name,mobile'); 
            $kv['status_name'] = $this->status[$kv['status']][0];
            $kv['type_name'] = $this->type[$kv['type']];
            $kv['customer_name'] = $cust[0]['name'];
            $kv['customer_mobile'] = $cust[0]['mobile'];

            //商品单处理
            if($kv['type']==2){
                $kv['goods_list'] = Db::table('order_list')->where('order_id',$kv['id'])->select()->toArray();
                foreach($kv['goods_list'] as &$goods){
                    $goods['image']=Db::table('specs')->where('id',$goods['specs_id'])->value('imgs');
                }
            }

            if($kv['status']==5){
                $kv['assess'] = Db::table('assess')->where('order_id',$kv['id'])->select()->toArray();
                $kv['assess'][0]['stars']=$this->stars[$kv['assess'][0]['val_total']];
            }

        }

        return json(['code'=>1,'data'=>$list]);
    }

    //商品
    public function goods_list(){
        $list = Db::table('goods')->where('status',1)->order('id')->select()->toArray();
        return json($list);
    }

    //订单流程中查询,用不同的状态区分所处流程
    public function index($status=''){
        $uid=Session::get('logonid');
        if(!$uid) header("location:/index.php/login");  

        $all=Request::param();
        
        $sdate = !empty($all['sdate'])?$all['sdate']:'';
        $edate = !empty($all['edate'])?$all['edate']:date('Y-m-d 23:59:59',time());
        if($edate<$sdate) return json('日期错误！');

        $view="";
        if(!empty($all['view'])) $view= $all['view'];
        $st=!empty($all['status'])?$all['status']:$status;

        //默认查询
        $query =Db::table("order");
        if($st) {
            $query->where('status','in',$st);
        }

        //部门权限
        $dept = new Dept();
        $my_depts = $dept->getMyDepts($uid);
        $arr =[];
        $dept_id='';
        foreach($my_depts as $dept){$arr[]=$dept['id'];}
        if(!empty($all['dept_id'])){
            $dept_id=$all['dept_id'];
            if(in_array($dept_id,$arr)){
                $arr=[$dept_id];
            }else{
                $arr=[];
            }
        }
        $my_depts = implode(",",$arr);
        $query->where('dept_id','in',$my_depts);

        //类型
        $type='';
        if(!empty($all['type'])){
            $type=$all['type'];
            $query->where('type',$all['type']);
        }
        //默认查询
        if(empty($all['sdate']) && empty($all['edate']) && empty($all['order_no'])){
            $query->where('create_time','between',[$sdate,$edate]);
        }

        if(!empty($all['order_no'])){
            $query->where('order_no',trim($all['order_no']));
        }

        if(!empty($all['sdate'])){
            $query->where('create_time','>=',trim($sdate));
        }
        if(!empty($all['edate'])){
            $query->where('create_time','<=',trim($edate));
        }

        $list = $query->order('id desc')->paginate(10)->toArray();

        foreach($list['data'] as &$kv){
            $kv['status_name'] = $this->status[$kv['status']];
            $kv['type_name'] = $this->type[$kv['type']];
            $kv['customer_id_name'] = Db::table('customer')->where('id',$kv['customer_id'])->value('name');
            if(!empty($kv['share_id'])){
                $kv['share_id_name'] = Db::table('customer')->where('id',$kv['share_id'])->value('name');
            }else{
                $kv['share_id_name']='';
            }

            $kv['dept_id_name'] = $this->dept[$kv['dept_id']]['name'];

        }

        //halt($this->type);
        $sys = Session::get("sys");
        View::assign(['sys'=>$sys,'list'=>$list,'dept'=>$this->dept,'dept_id'=>$dept_id,'status'=>$status,'types'=>$this->type,'type'=>$type,'cst'=>$st]);
        
        return View::fetch($view);

    }  

    //订单流程操作,传入id,status
    public function order_check(){
        $uid=Session::get('logonid');
        if(!$uid) header("location:/index.php/login");   
        $all=Request::param(); //halt($all);

        if(empty($all['status'])) return json('无效的状态！');
        $status =$all['status'];

        //确认操作
        if($_POST){
            if(empty($all['id'])) return json(['code'=>0,'msg'=>'error!']);
            $oo = Db::table('order')->find($all['id']);
            if(!$oo) json(['code'=>0,'msg'=>'error!']);
            if($oo['status']==$all['status']) return json(['code'=>0,'msg'=>'状态不正确!'.$oo['status']]);

            //update order status
            $res = Db::table('order')->update(['id'=>$all['id'],'status'=>$status]);

            //insert order log
            Db::table('order_log')->insert(array(
                'order_id'=>$all['id'],
                'name'=>$this->status[$all['status']][0],  //'确认订单',
                'creater'=>$uid,
                'create_time'=>date('Y-m-d H:i:s',time())
            ));
            return json(['code'=>1,'msg'=>'订单已确认！']);
        }


        $view="";
        if(!empty($all['view'])) $view= $all['view'];
        
        //显示页面
        $sdate = !empty($all['sdate'])?$all['sdate']:date('Y-m-d 00:00:00',time()-10*24*3600);
        $edate = !empty($all['edate'])?$all['edate']:date('Y-m-d 23:59:59',time());
        if($edate<$sdate) return json('日期错误！');

        //默认查询
        $query =Db::table("order")->where('status',$status);
        if(empty($all['sdate']) && empty($all['edate']) && empty($all['order_no'])){
            $query->where('create_time','between',[$sdate,$edate]);
        }
        if(!empty($all['order_no'])){
            $query->where('order_no',trim($all['order_no']));
        }
        if(!empty($all['sdate'])){
            $query->where('create_time','>=',trim($sdate));
        }
        if(!empty($all['edate'])){
            $query->where('create_time','<=',trim($edate));
        }

        $list = $query->order('id desc')->paginate(15)->toArray();

        foreach($list['data'] as &$kv){
            $kv['status_name'] = $this->status[$kv['status']][0];
            $kv['truck_type_name'] = $this->cat[$kv['truck_type']]['name'];
            $kv['type_name'] = $this->type[$kv['type']];
            $kv['creater_name'] = Db::table('customer')->where('id',$kv['creater'])->value('name');
            $kv['driver_id_name'] = Db::table('customer')->where('id',$kv['driver_id'])->value('name');
        }

        $sys = Session::get("sys");
        View::assign([
            'sys'=>$sys,
            'status'=>$all['status'],
            'list'=>$list,
            'sdate'=>$sdate,
            'edate'=>$edate]
        );
        
        return View::fetch($view);

    }  


    //订单综合查询
    public function order_query(){
        if(!Session::get('logonid')) header("location:/index.php/login/target/admin");  


        $all=Request::param();
        
        $sdate = !empty($all['sdate'])?$all['sdate']." 00:00:00":date('Y-m-d 00:00:00',time()-6*24*3600);
        $edate = !empty($all['edate'])?$all['edate']." 23:59:59":date('Y-m-d 23:59:59',time());
        if($edate<$sdate) return json('日期错误！');

        $dated = number_format((strtotime($edate)-strtotime($sdate))/3600/24,0) ;
        if($dated>31) return json('查询时间段最多一个月！');

        $creater=!empty($all['creater'])?$all['creater']:'';
        $status=!empty($all['status'])?$all['status']:'';
        $payment=!empty($all['payment'])?$all['payment']:'';

               
        //默认查询
        $query = Db::table("order");
        if($status!=''){
            $query->where('status',$status);
        }
         if(empty($all['sdate']) && empty($all['edate']) && empty($all['order_no'])){
             $query->where('create_time','between',[$sdate,$edate]);
         }
         if(!empty($all['order_no'])){
             $query->where('order_no',trim($all['order_no']));
         }
         if(!empty($all['sdate'])){
             $query->where('create_time','>=',trim($sdate));
         }
         if(!empty($all['edate'])){
             $query->where('create_time','<=',trim($edate));
         }

         if(!empty($all['creater'])){
             $query->where('creater',$creater);
         } 
         if(!empty($all['payment'])){
             $query->where('payment',$all['payment']);
         }
          

        $list = $query->select()->toArray();
        //halt($list);

        $count=0;
        $price1=0;
        $price2=0;
        $commision=0;

        foreach($list as &$kv){
            $count++;
            $price1+=$kv['price1'];
            $price2+=$kv['price2'];
            $commision+=$kv['commision'];

            $kv['status_name'] = $this->status[$kv['status']][0];
            $kv['type_name'] = $this->type[$kv['type']];
            $kv['customer_id_name'] = Db::table('customer')->where('id',$kv['customer_id'])->value('name');
            $kv['trainer_id_name'] = Db::table('customer')->where('id',$kv['trainer_id'])->value('name'); 
      
        }


        $sys = Session::get("sys");
        $data=[
            'sys'=>$sys,
            'list'=>$list,
            'user'=>$this->users,
            'status_arr'=>$this->status,
            'status'=>$status,
            'creater'=>$creater,
            'sdate'=>$sdate,
            'edate'=>$edate,
            'payments'=>$this->payment,
            'payment'=>$payment,
            'price1'=>number_format($price1,2),
            'price2'=>number_format($price2,2),
            'commision'=>number_format($commision,2),
            'count'=>$count
        ]; 
        //halt($data);
        View::assign($data);
        
        return View::fetch();

    }  

    //订单操作记录
    public function order_log(){
        if(!Session::get('logonid')) header("location:/index.php/login");               

        $all =Request::param();
        if(empty($all['id'])) return 'Invalid order id!';
        $id=$all['id'];
        
        $order = Db::table('order')->find($id);
        if(!$order) return '无效的订单！';
        $order['creater_name'] = $this->users[$order['creater']]['name'];
        $order['status_name']=$this->status[$order['status']];

        $list=Db::table('order_log')->where('order_id',$id)->select()->toArray();
        foreach($list as &$log){
            if($log['creater']) $log['creater_name'] = $this->users[$log['creater']]['name'];
        }


        View::assign(['order'=>$order,'list'=>$list]);
        return View::fetch('order_log');
    }

    public function order_flow(){
        $sys = Db::table('sys')->find(1);
       View::assign(['list'=>$this->status,'sys'=>$sys]);
       return View::fetch();
    }
    public function get_status(){
        $uid = Session::get('logonid');
        if(!$uid) {
            return header("location:/index.php/login/customer_login");
        }

        return json_encode(['code'=>1,'status'=>$this->status]);
    }

    //购物车
    public function cart(){
        $all=Request::param();

        if($_SERVER['SERVER_ADDR']=='127.0.0.1'){
            $customer=Db::table('customer')->find(1075);
        }else{
            if(empty($all['token'])){
                return json(['code'=>0,'msg'=>'需要token!']);
            }            
            $token = new Token();
            $arr = $token->check_token($all['token']);
            if(!$arr['code']){
                return json($arr['msg']);
            }
            $customer=$arr['customer'];
        }

        if(!empty($all['remove_id'])){
            Db::table('cart')->where('customer_id',$customer['id'])->where('id','in',implode(",",$all['remove_id']))->delete();
        }

        //加入购物车
        if(!empty($all['goods'])){
            $all['goods']= json_decode($all['goods'],true);
            $res =0;
            foreach($all['goods'] as &$row){
                $row['customer_id']=$customer['id'];
                $goods =Db::table('goods')->find($row['goods_id']);
                if($row['specs_id']){
                    $price = Db::table("specs")->where('id',$row['specs_id'])->value('price');
                }else{
                    $price = $goods['price1'];
                }
                $row['total']=$price*$row['num'];
                $row['create_time'] = date('Y-m-d');
                $row['dept_id']=$goods['dept_id'];

                //购物车已存在商品
                $exist_sp=Db::table('cart')->where('specs_id',$row['specs_id'])->find();
                if(!empty($exist)){
                    $row['id']=$exist_sp['id'];
                    $res+= Db::table('cart')->update($row);
                }else{
                    $res+=Db::table('cart')->insert($row);
                }
            }

            return json(['code'=>1,'msg'=>$res."件已加购物车!"]);
        }
 
        //查询购物车
        $list = Db::table('cart')->where('customer_id',$customer['id'])->select()->toArray();
        $arr=[];
        foreach($list as &$row){
            $arr[$row['dept_id']]['shop_name']=$this->dept[$row['dept_id']]['name'];

            $sql="select a.name,b.name as spec_name,b.price,b.imgs from goods a left join specs b on a.id=b.goods_id where b.id=?";
            $record =Db::query($sql,[$row['specs_id']]);
            if(count($record)){
                $record=$record[0];
                $row['name']    =$record['name'];
                $row['spec_name']    =$record['spec_name'];
                $row['price']   =$record['price'];
                $row['image']   =$record['imgs'];
            }
            $arr[$row['dept_id']]['goods'][]=$row;
        }


        return json(['data'=>$arr]);
    }

    //商品单下单
    public function order_addx(){
        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'请登录后，再下单！(token error)!']);
        }
        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }
        $customer=$arr['customer'];

        if(empty($all['goods']) ){
            return json(['code'=>'0','msg'=>'请选择商品!']);
        }

        if(empty($all['address']) ){
            return json(['code'=>'0','msg'=>'请选择收货地址!']);
        }

        // //防止下垃圾单
        // $cancel_limit  = Db::table('sys')->where('id',1)->value('cancel_limit'); 
        // if(!$cancel_limit) $cancel_limit==3;
    
        //处理商品,价格
        $price=0;
        $goods_list_str = [];
        $order_list=[];
        $order_dept_id=null;

        foreach($all['goods'] as $goods){
            $goods_db = Db::table('goods')->find($goods['id']);
            $order_dept_id=$goods_db['dept_id'];
            $goods['name']=$goods_db['name'];
            //如果有规格就用规格参数，否则就用商品基本参数。
            if(!empty($goods['specs_id'])){
                $goods_sp =Db::table('specs')->find($goods['specs_id']); 
                $goods['name'].=("【".$goods_sp['name']."】");
                $goods_db['price1']=$goods_sp['price'];
            }
            //商品价格小计
            $gprice = $goods_db['price1']*$goods['cnt'];

            $str = $goods['name']."x".$goods['cnt'];
            $goods_list_str[]=$str; //商品列表
            $price += $gprice;  //商品价格

            //订单商品表
            $order_list[]=array(
                'goods_id'=>$goods['id'],
                'name'=>$goods['name'],
                'specs_id'=>$goods['specs_id'],
                'price'=>$goods_db['price1'],
                'num'=>$goods['cnt'],
                'total'=>$gprice,
                'create_time'=>date('Y-m-d H:i:s'),
                'creater'=>$customer['id']
            );

        }

        $goods_list_str = implode(",",$goods_list_str);

        //取得新的流水号order
        $om = new OrderModel();
        $order_no =date('Ymd')."_".Common::randomString(5);
        if(!$order_dept_id) return json(['code'=>0,'msg'=>'无店铺资料，下单失败！']);

        //准备订单内容，写入订单并取得id号
        $row=array(
            'type'=>2,
            'order_no'=>$order_no,
            'create_time'=>date("Y-m-d H:i:s"),
            'price1'=>$price,
            'price2'=>0,
            'status'=>1,
            'customer_id'=>$customer['id'],
            'goods_list'=>$goods_list_str,
            'memo'=>$all['memo'],
            'dept_id'=>$order_dept_id
        );

        //商品分享，佣金计算
        if(!empty($all['share_mobile'])){
            $row['share_id']=Db::table('customer')->where('mobile',trim($all['share_mobile']))->value('id');
            $com_set=Db::table('sys')->where('id',1)->value('commision');
            if($com_set){
                $row['commision']=$row['price1']*$com_set;
            }
        }

        $order_id =$om->insertGetId($row);

        //快递表
        $express=array(
            'order_id'=>$order_id,
            'contact'=>!empty($all['contact'])?$all['contact']:$customer['name'],
            'mobile'=>!empty($all['mobile'])?$all['mobile']:$customer['mobile'],
            'address'=>$all['address'],
            'create_time'=>date('Y-m-d H:i:s')
        );
        Db::table('express')->insert($express);

        //写入订单日志表
        $res = Db::table('order_log')->insert(array(
            'order_id'=>$order_id,
            'name'=>'客户下单:'.$row['order_no'],
            'creater'=>2,
            'create_time'=>date('Y-m-d H:i:s',time())
        ));

        //写入订单明细表
        foreach($order_list as &$row){
            $row['order_id']=$order_id;
            Db::execute("delete from cart where customer_id=? and specs_id=?",[$customer['id'],$row['specs_id']]);
        }
        Db::table('order_list')->insertAll($order_list);

        return json(['code'=>$res,'msg'=>'下单成功!']);
    }


    //商品订单处理
    public function order_takex(){
        $all=Request::param();

        //订单处理
        if(empty($all['id']) || empty($all['status'])){
            return json(['code'=>0,'msg'=>'缺少订单id或者status参数.']);
        }

        $id = $all['id'];
        if(!in_array($all['status'],array(1,2,3,4,5,10,20))){
            return json(['code'=>0,'msg'=>'订单不能操作，状态：'.$this->status[$all['status']][0]]);
        }

        $order=Db::table('order')->find($id);
        $arr = array('id'=>$all['id'],'status'=>$all['status']);

        //客人
        if(!empty($all['token'])){

            $token = new Token();
            $arr1 = $token->check_token($all['token']);
            if(!$arr1['code']){
                return json($arr1['msg']);
            }
            $customer=$arr1['customer'];

            if($order['status']==$all['status']){
                return json(['code'=>0,'msg'=>'订单状态重复：'.$this->status[$all['status']][0]]);
            }

            //取消
            if($all['status']==10){
                if($order['status']>=2){
                    return json(['code'=>0,'msg'=>'订单已付款或发货，不能取消！']);
                }
                $arr['cancel_time']=date('Y-m-d H:i:s');
                $log=array('order_id'=>$order['id'],'name'=>'客户取消','create_time'=>date('Y-m-d H:i:s'));
            }

            //发货
            if($all['status']==3){
                if($order['status']!=2) return json(['code'=>0,'msg'=>"不是待发货订单！"]);

                if(!empty($all['package_no'])){
                    $arr['package_no']=$all['package_no'];
                }
                $arr['sent_time'] = date('Y-m-d H:i:s');
                $log=array('order_id'=>$order['id'],'name'=>'订单已发货','create_time'=>date('Y-m-d H:i:s'));

                //更新商品销量
                $order_list = Db::table('order_list')->where('order_id',$order['id'])->select()->toArray();
                foreach($order_list as $row){
                    Db::execute('update goods set sales=sales+? where id=?',array($row['num'],$row['goods_id']));
                }
            }

            //订单收货
            if($all['status']==4){
                if($order['status']!=3){
                    return json(['code'=>0,'msg'=>'订单不在发货状态！']);
                }
                $arr['receive_time']=date('Y-m-d H:i:s');                
                $log=array('order_id'=>$order['id'],'name'=>'客户签收','create_time'=>date('Y-m-d H:i:s'));
            }

            //退货
            if($all['status']==6){
                if($order['status']!=5 && $order['status']!=4){
                    return json(['code'=>0,'msg'=>'还不能退货哦！']);
                }
                $arr['return_time']=date('Y-m-d H:i:s');
                $log=array('order_id'=>$order['id'],'name'=>'客户退货','create_time'=>date('Y-m-d H:i:s'));
            }

            Db::table('order_log')->insert($log);            
            $res=Db::table('order')->save($arr);
            return json(['code'=>$res,'msg'=>$res>0?'成功':'失败']);
        }

        //店铺
        $uid=Session::get('logonid');
        if(empty($uid)){
            return header("location:/index.php/login");
        }

        //取消
        if($all['status']==20){
            if($order['status']>2) return json(['code'=>0,'msg'=>"不能取消！"]);
            $log=array('order_id'=>$order['id'],'name'=>'商家取消','create_time'=>date('Y-m-d H:i:s'));
            $arr['cancel_time']=date('Y-m-d H:i:s');
        }
        
        //发货
        if($all['status']==3){
            if($order['status']!=2) return json(['code'=>0,'msg'=>"不是待发货订单！"]);

            if(!empty($all['package_no'])){
                $arr['package_no']=$all['package_no'];
            }
            $arr['sent_time'] = date('Y-m-d H:i:s');
            $log=array('order_id'=>$order['id'],'name'=>'订单已发货','create_time'=>date('Y-m-d H:i:s'));

            //更新商品销量
            $order_list = Db::table('order_list')->where('order_id',$order['id'])->select()->toArray();
            foreach($order_list as $row){
                Db::execute('update goods set sales=sales+? where id=?',array($row['num'],$row['goods_id']));
            }
        }        

        //halt($log,$arr);
        Db::table('order_log')->insert($log);
        Db::table('order')->save($arr);

        return header('location:/index.php/order/index');

    }

}
